<template>
  <div class="pet-product-page">
    <!-- 搜索栏 -->
    <van-search
      v-model="searchValue"
      placeholder="搜索宠物商品..."
      shape="round"
      @search="onSearch"
      @clear="onClearSearch"
      @input="handleInputSearch"
    >
    </van-search>

    <!-- 搜索结果区域 -->
    <div v-if="hasSearchValue" class="search-result-section">
      <div class="search-result-header">
        <span class="result-title">搜索结果: "{{ searchValue }}"</span>
        <span v-if="filteredProducts.length > 0" class="result-count">({{ filteredProducts.length }})</span>
        <van-button 
          size="mini" 
          type="text" 
          @click="clearSearchResult"
          class="clear-result-btn"
        >
          清除
        </van-button>
      </div>
      
      <van-empty 
        v-if="filteredProducts.length === 0 && !searchLoading" 
        description="没有找到匹配的商品" 
      />
      
      <van-loading v-if="searchLoading" color="#1989fa" class="search-loading" />
      
      <van-list 
        v-else
        :finished="true"
        finished-text="没有更多结果"
        class="search-result-list"
      >
        <van-cell
          v-for="item in filteredProducts"
          :key="item.productId"
          class="search-result-item"
          @click="goProductDetail(item)"
        >
          <template #icon>
            <van-image 
              :src="item.imageUrl"  
              alt="商品图片" 
              class="result-img"
              fit="cover"
            />
          </template>
          <div class="result-info">
            <h3 class="result-name">
              <span v-html="highlightMatch(item.productName)"></span>
            </h3>
            <p class="result-desc">{{ item.description }}</p>
            <p class="result-price">¥{{ item.price?.toFixed(2) }} 元</p>
          </div>
        </van-cell>
      </van-list>
    </div>

    <!-- 原页面内容（标签栏、广告、热卖推荐）- 仅在无搜索时显示 -->
    <div v-else>
      <!-- 标签栏 -->
      <van-tabs v-model:active="activeTab" @change="handleTabChange">
        <van-tab title="推荐" />
        <van-tab title="大牌" />
        <van-tab title="保险" />
        <van-tab title="流量" />
      </van-tabs>
      
      <!-- 广告图 -->
      <van-swipe :autoplay="3000" indicator-color="white" class="ad-swipe">
        <van-swipe-item>
          <div class="ad-container">
            <img
              :src="avatarUrl"
              class="ad-img"
            />
          </div>
        </van-swipe-item>
      </van-swipe>
      
      <!-- 热卖推荐 -->
      <div class="hot-sell">
        <div class="hot-sell-title">
          <span>热卖推荐</span>
          <van-button round size="small" @click="viewAllProducts">查看更多</van-button>
        </div>
        
        <!-- 加载状态 -->
        <van-loading v-if="loading" color="#1989fa" class="loading" />
        
        <!-- 错误提示 -->
        <van-empty 
          v-else-if="error" 
          description="获取商品失败，请重试" 
        >
          <template #bottom>
            <van-button type="primary" size="small" @click="fetchProducts">重新加载</van-button>
          </template>
        </van-empty>
        
        <!-- 商品列表 -->
        <van-list v-else :loading="loading" :finished="finished" finished-text="没有更多商品了">
          <van-cell
            v-for="(item, index) in hotSellList"
            :key="item.productId"
            class="product-item"
            @click="goProductDetail(item)"
          >
            <template #icon>
              <div class="product-img-container">
                <van-image 
                  :src="item.imageUrl"  
                  alt="商品图片" 
                  class="product-img"
                  fit="cover"
                />
              </div>
            </template>
            <div class="product-info">
              <h3 class="product-name">{{ item.productName }}</h3>
              <p class="product-desc">{{ item.description }}</p>
              <p class="product-price">¥{{ item.price?.toFixed(2) }} 元</p>
            </div>
          </van-cell>
        </van-list>
      </div>
    </div>
  </div>
</template>

<script setup name="PetShop">
import { ref, onMounted, watch, computed } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { queryALLProducts } from '../api/index';
import avatarImg from '../assets/petshop.png';

const router = useRouter();
const avatarUrl = ref(avatarImg)
const searchValue = ref('');
const activeTab = ref(0);
const hotSellList = ref([]);
const allProducts = ref([]); // 存储所有商品，用于搜索过滤
const filteredProducts = ref([]); // 搜索过滤后的商品
const loading = ref(false);
const error = ref(false);
const currentCategory = ref('all');
const finished = ref(false);
const searchLoading = ref(false); // 搜索加载状态

// 判断是否有搜索内容
const hasSearchValue = computed(() => {
  return searchValue.value.trim().length > 0;
});

// 获取商品数据
const fetchProducts = async (category = 'all') => {
  try {
    loading.value = true;
    error.value = false;
    finished.value = false;
    
    let response;
    if (category === 'all') {
      response = await queryALLProducts(); 
    } else {
      // 按类别查询（实际项目中实现）
      response = await queryALLProducts();
    }
    
    if (!response || !Array.isArray(response)) {
      throw new Error('接口返回格式异常');
    }  
    
    // 过滤已删除商品
    const validProducts = response.filter(item => item.isDeleted !== 1);
    hotSellList.value = validProducts.slice(0, 4);
    allProducts.value = validProducts; // 保存所有商品用于搜索
    finished.value = true;
  } catch (err) {
    console.error('获取商品失败:', err);
    error.value = true;
    hotSellList.value = [];
    allProducts.value = [];
    showToast('获取商品失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 处理输入框实时搜索
const handleInputSearch = async (value) => {
  // 1. 先将 value 转为字符串并去除首尾空格（关键：确保后续操作的是字符串）
  const inputValue = String(value || '').trim();
  
  if (!inputValue) {
    filteredProducts.value = [];
    return;
  }
  
  searchLoading.value = true;
  setTimeout(() => {
    // 2. 过滤逻辑中使用转换后的 inputValue（确保是字符串）
    filteredProducts.value = allProducts.value.filter(item => {
      // 对 inputValue 调用 toLowerCase()
      const searchStr = inputValue.toLowerCase();
      // 商品名称匹配
      const nameMatch = item.productName.toLowerCase().includes(searchStr);
      // 商品描述匹配（先判断 description 存在）
      const descMatch = item.description 
        ? item.description.toLowerCase().includes(searchStr) 
        : false;
      return nameMatch || descMatch;
    });
    searchLoading.value = false;
  }, 300);
};

// 执行搜索（点击搜索按钮）
const onSearch = (value) => {
  if (!value.trim()) {
    showToast('请输入搜索内容');
    return;
  }
  handleInputSearch(value);
};

// 清除搜索
const onClearSearch = () => {
  searchValue.value = '';
  filteredProducts.value = [];
  // 重置商品列表
  fetchProducts(currentCategory.value);
};

// 清除搜索结果
const clearSearchResult = () => {
  onClearSearch();
};

// 高亮显示匹配的文本
const highlightMatch = (text) => {
  if (!searchValue.value.trim()) return text;
  
  const reg = new RegExp(`(${searchValue.value})`, 'gi');
  return text.replace(reg, '<span class="highlight">$1</span>');
};

// 标签切换
const handleTabChange = (index) => {
  const categoryMap = ['all', 'brand', 'insurance', 'traffic'];
  currentCategory.value = categoryMap[index];
  fetchProducts(currentCategory.value);
};

// 查看更多商品
const viewAllProducts = () => {
};

// 前往商品详情
const goProductDetail = (item) => {
  router.push({
    path: '/productDetail',
    query: { id: item.productId }
  });
};

onMounted(() => {
  fetchProducts(currentCategory.value);
});

// 监听搜索值变化
watch(searchValue, (newVal) => {
  if (newVal.trim()) {
    handleInputSearch(newVal);
  } else {
    filteredProducts.value = [];
  }
});
</script>

<style scoped>
.pet-product-page {
  background-color: #fff;
  min-height: 100vh;
}

.van-search {
  margin: 10px;
  --van-search-input-height: 36px;
}

.van-tabs {
  margin: 0 10px;
  --van-tabs-bottom-bar-color: #FFD700;
  --van-tab-active-text-color: #333;
}

.ad-swipe {
  margin: 0 10px;
  border-radius: 8px;
  overflow: hidden;
}

.ad-container {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.ad-img {
  width: 100%;
  height: 100px;
  border-radius: 8px;
  object-fit: cover;
}

.hot-sell {
  margin: 15px 10px 10px;
}

.hot-sell-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 0 5px;
}

.hot-sell-title span {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 10px 5px;
  border-bottom: 1px solid #f2f2f2;
}

.product-img-container {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 10px;
}

.product-img {
  width: 100%;
  height: 100%;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  text-align: left;
  margin: 0; 
  padding: 0; 
}

.product-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-top: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-desc {
  font-size: 12px;
  color: #999;
  margin-top: 0px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}

.product-price {
  font-size: 14px;
  color: #f00;
  font-weight: 500;
  margin-top: auto;
}

.loading {
  padding: 30px 0;
  text-align: center;
}

/* 搜索结果样式 */
.search-result-section {
  padding: 0 10px;
  margin-top: 10px;
}

.search-result-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
}

.result-title {
  font-size: 16px;
  color: #333;
}

.result-count {
  font-size: 14px;
  color: #666;
  margin-left: 5px;
}

.clear-result-btn {
  color: #666;
}

.search-result-list {
  background-color: #fff;
}

.search-result-item {
  padding: 10px 5px;
  border-bottom: 1px solid #f5f5f5;
}

.result-img {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}

.result-info {
  flex: 1;
  padding-left: 10px;
}

.result-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.result-desc {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;

}

.result-price {
  font-size: 14px;
  color: #f00;
  font-weight: 500;
}

.highlight {
  color: #ff4d4f;
  font-weight: bold;
}

.search-loading {
  padding: 30px 0;
  text-align: center;
}
</style>
    